/* eslint-disable array-callback-return */
import React, { Component } from 'react';
import { Layout, Menu, Icon } from 'antd';
import { NavLink } from 'umi';
// 引入侧边栏配置文件
import tooliddef from '../../../config/tooliddef';
import styles from '../index.less';

const { SubMenu } = Menu;
const { Sider } = Layout;

export default class Aside extends Component {
  // 可展开节点选项
  rootSubmenuKeys = [];

  state = {
    openKeys: [],
  };

  componentDidMount() {
    this.rootSubmenuKeys = tooliddef.map(x => {
      if (x.menus.length) return x.key;
    });
  }

  // 每次只允许展开一个折叠项
  handleOpen = openKeys => {
    const latestOpenKey = openKeys.find(key => this.state.openKeys.indexOf(key) === -1);
    if (this.rootSubmenuKeys.indexOf(latestOpenKey) === -1) {
      this.setState({ openKeys });
    } else {
      this.setState({
        openKeys: latestOpenKey ? [latestOpenKey] : [],
      });
    }
  }

  // 点击单项时应当关闭展开项
  handleClickMenuItem = item => {
    const { key } = item;
    // 判断 当前item是否为单个节点
    const target = tooliddef.find(x => x.key === key);
    if (target) this.setState({ openKeys: [] });
  }

  render() {
    return (
      <div>
        <Sider width={200} className={styles.sider}>
          <Menu
            mode="inline"
            defaultSelectedKeys={['0000']}
            // defaultOpenKeys={['sub1']}
            openKeys={this.state.openKeys}
            onOpenChange={this.handleOpen}
            style={{ height: '100%', borderRight: 0 }}
            onClick={this.handleClickMenuItem}
          >
            {
              tooliddef.map(ele => {
                return (ele.menus.length ?
                  <SubMenu
                    key={ele.key}
                    title={<span>{ele.title}<Icon style={{ paddingLeft: 30 }} type={ele.icon} /></span>}
                  >
                    {
                      ele.menus.map(menu => {
                        return (
                          <Menu.Item key={menu.key}>
                            <NavLink to={menu.link}>{menu.title}</NavLink>
                          </Menu.Item>
                        )
                      })
                    }
                  </SubMenu>
                  : <Menu.Item key={ele.key}>
                    {/* <div> */}
                    <NavLink to={ele.link}>{ele.title}
                      <Icon style={{ paddingLeft: 30 }} type={ele.icon} />
                    </NavLink>
                    {/* </div> */}
                  </Menu.Item>
                )
              })
            }
          </Menu>
        </Sider>
      </div >
    );
  }
}
